<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<style>
    .image-upload {display: none;}
    #previewImage{cursor: pointer}
</style>
<body>
    <div>

    </div>
    <div class="image">
        <fieldset>
            <legend>图片上传</legend>
            <img th:src="@{/image/upload.png}"  alt="上传图片占位符" id="previewImage" th:onclick="uploadImg();" width="120px" height="120px"/>
            <input class="image-upload" type="file" accept="image/*" id="imageFile"/>
        </fieldset>
    </div>
<!--    <div class="file">
        <fieldset>
            <legend>文件上传</legend>
            <input class="file-upload" type="file" id="file"/>
            <input type="button" value="上传文件" th:onclick="uploadFile();"/>
        </fieldset>
    </div>-->
    <div id="uploadResult"></div>
</body>
</html>




<script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    var xmlHttp;
    var uploadUrl = /*[[@{/file/upload}]]*/ null;
    var uploadUrlPage = /*[[@{/admin/file/fileUpload}]]*/ null;
    var imgUploadSrc = /*[[@{/image/upload.png}]]*/ null;

    var imageInput = document.getElementById('imageFile');
    var fileInput = document.getElementById('file');
    var previewImage = document.getElementById('previewImage')
    var uploadResult = document.getElementById('uploadResult');

    var isSubmited = false

    // 监听器只注册一次
    document.addEventListener('DOMContentLoaded', function () {
        var imageInputHandler = function (event) {
            var image = event.target.files[0];
            if (!image) {
                return;
            }
            var reader = new FileReader();
            // 文件读取成功时的回调
            reader.onload = function (e) {
                // e.target.result 是一个包含图片数据的URL
                previewImage.src = e.target.result;
                previewImage.style.display = 'block';
                submitFile(image);
                reader.onload = null; // 清除 onload 回调函数
            };
            // 开始读取指定的Blob或File对象
            reader.readAsDataURL(image);
        };
        imageInput.addEventListener('change', imageInputHandler);
    });


    // 图片预览及上传
    var uploadImg = function () {
        uploadResult.innerHTML= null;
        imageInput.click();
    }

    // 文件上传
    var uploadFile = function () {
        uploadResult.innerHTML= null;
        if(fileInput.files.length>0) {
            let file = fileInput.files[0];
            submitFile(file);
        } else {
            alert("请先选择文件")
        }
    }

    var submitFile = function(file) {
        if(isSubmited) {
            return;
        }
        // 发送到后端
        var formData = new FormData();
        formData.append('file', file);
        fetch(uploadUrl,{
            method:'POST',
            body:formData,
            headers:{},
        })
        .then(response => {
            if(!response.ok) {
                throw new Error('网络错误');
            }
            return response.json();
        })
        .then(data => {
            console.log('文件上传成功:'+JSON.stringify(data));
            let result = JSON.stringify(data);
            uploadResult.innerHTML=`<p>${result}</P>`;
            if(data.code == 200) {
                isSubmited = true;
                alert("文件 "+data.data.fileName+" 上传成功!");
                window.location.href= uploadUrlPage
            }
        })
        .catch(error => {
            console.error('文件上传失败:', error);
        });
    }
    /*]]>*/
</script>
